﻿using EvaluationSystem.Filters;
using EvaluationSystem.Models;
using EvaluationSystem.Utils;

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EvaluationSystem.Apis
{
    [Route("api/[controller]/[action]")]
    [AuthorizationFilter]
    public class ApiBaseController<TController> : ControllerBase where TController : class
    {
        protected readonly ILogger<TController> _logger;
        protected readonly MyDbContext _dbContext;

        // 测试用户id
        private static int _testPeopleId = 3;

        public ApiBaseController(ILogger<TController> logger, MyDbContext dbContext)
        {
            _logger = logger;
            _dbContext = dbContext;
        }

        public bool GetUserToken(out byte[]? value)
        {
            var r = SessionToken.GetUserToken(HttpContext, out var val);
            value = val;
            return r;
        }

        public bool GetUserToken<T>(out T value) where T : class, new()
        {
            var r = SessionToken.GetUserToken(HttpContext, out T? val);
#if DEBUG
            value = val ?? _dbContext.People.FirstOrDefault(t => t.PeopleId == _testPeopleId) as T ?? new T();
#else
            value = val ?? throw new ArgumentNullException(nameof(val)) ;
#endif
            return r;
        }

        public void SetUserToken(object? obj)
        {
            SessionToken.SetUserToken(HttpContext, obj);
        }
    }
}
